package com.cc.servlet;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import com.cc.entity.Department;
import com.cc.service.DepartmentService;
import com.cc.service.impl.DepartmentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author CC
 * @version 1.0
 * @description: TODO
 * @date 2025/4/21 10:35
 */
@WebServlet("/department")
public class DepartmentServlet extends HttpServlet {
    private DepartmentService departmentService = new DepartmentServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置响应编码
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        //允许所有来源访问 解决跨域问题
        resp.addHeader("Access-Control-Allow-Origin","*");
        //允许访问的方式
        resp.addHeader("Access-Control-Allow-Method","POST,GET");
        //获取请求参数
        String method = req.getParameter("method")==null?"list":req.getParameter("method");
        switch (method){
            case "list":
                list(req,resp);
                break;
            default:
                break;
        }


    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取部门列表
        List<Department> departmentList = departmentService.getDepartmentList();
        //转为json格式
        String jsonString = JSON.toJSONString(departmentList, JSONWriter.Feature.WriteMapNullValue);
        resp.getWriter().write(jsonString);
    }
}
